<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(C卷,100分)- 滑动窗口最大和（Java & JS & Python & C）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>有一个N个整数的数组&#xff0c;和一个长度为M的窗口&#xff0c;窗口从数组内的第一个数开始滑动直到窗口不能滑动为止&#xff0c;</p> 
<p>每次窗口滑动产生一个窗口和&#xff08;窗口内所有数的和&#xff09;&#xff0c;求窗口滑动产生的所有窗口和的最大值。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<ul><li>第一行输入一个正整数N&#xff0c;表示整数个数。&#xff08;0&lt;N&lt;100000&#xff09;</li><li>第二行输入N个整数&#xff0c;整数的取值范围为[-100,100]。</li><li>第三行输入一个正整数M&#xff0c;M代表窗口的大小&#xff0c;M&lt;&#61;100000&#xff0c;且M&lt;&#61;N。</li></ul> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<ul><li>窗口滑动产生所有窗口和的最大值。</li></ul> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">6<br /> 10 20 30 15 23 12<br /> 3</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">68</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;"> <p>窗口长度为3&#xff0c;窗口滑动产生的窗口和分别为</p> <p>10&#43;20&#43;30&#61;60&#xff0c;</p> <p>20&#43;30&#43;15&#61;65&#xff0c;</p> <p>30&#43;15&#43;23&#61;68&#xff0c;</p> <p>15&#43;23&#43;12&#61;50&#xff0c;</p> <p>所以窗口滑动产生的所有窗口和的最大值为68。</p> </td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>此题应该是考察我们如何计算新的滑动窗口的值&#xff0c;一般有两种方式&#xff1a;</p> 
<p>1、将滑动窗口中的元素值相加求和</p> 
<p>2、基于前一个滑动窗口的和sum&#xff0c;计算新的滑动窗口的和&#xff0c;原理如下</p> 
<p><img alt="" height="213" src="https://img-blog.csdnimg.cn/3f648694ca7847c980fcb75583e11164.png" width="395" /></p> 
<p>如上图所示&#xff0c;第二个滑动窗口&#xff0c;相当于第一个滑动窗口减去10&#xff0c;加上15。</p> 
<p>公式如下&#xff1a;i为第二个滑动窗口的起点索引&#xff0c;sum为第一个滑动窗口的和</p> 
<p>sum &#61; sum - arr[i - 1] &#43; arr[i &#43; m - 1];</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 3) {
    const n &#61; lines[0] - 0;
    const arr &#61; lines[1].split(&#34; &#34;).map(Number);
    const m &#61; lines[2] - 0;

    console.log(getMaxWindowSum(arr, n, m));

    lines.length &#61; 0;
  }
});

function getMaxWindowSum(arr, n, m) {
  let sum &#61; arr.slice(0, m).reduce((p, c) &#61;&gt; p &#43; c);
  let ans &#61; sum;

  for (let i &#61; 1; i &lt;&#61; n - m; i&#43;&#43;) {
    sum &#43;&#61; arr[i &#43; m - 1] - arr[i - 1];
    ans &#61; Math.max(ans, sum);
  }

  return ans;
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Scanner;

public class Main {
  // 输入获取
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; sc.nextInt();

    int[] arr &#61; new int[n];
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      arr[i] &#61; sc.nextInt();
    }

    int m &#61; sc.nextInt();

    System.out.println(getResult(n, arr, m));
  }

  // 算法入口
  public static int getResult(int n, int[] arr, int m) {
    int sum &#61; 0;
    for (int i &#61; 0; i &lt; m; i&#43;&#43;) { // 初始滑窗内部和
      sum &#43;&#61; arr[i];
    }

    int ans &#61; sum;

    for (int i &#61; 1; i &lt;&#61; n - m; i&#43;&#43;) {
      sum &#43;&#61; arr[i &#43; m - 1] - arr[i - 1]; // 基于初始滑窗进行差异求和&#xff0c;避免O(n)求和
      ans &#61; Math.max(ans, sum);
    }

    return ans;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
n &#61; int(input())
arr &#61; list(map(int, input().split()))
m &#61; int(input())


# 算法入口
def getResult():
    sumV &#61; sum(arr[:m])
    ans &#61; sumV

    for i in range(1, n-m&#43;1):
        sumV &#43;&#61; arr[i&#43;m-1] - arr[i-1]
        ans &#61; max(ans, sumV)

    return ans


# 算法调用
print(getResult())
</code></pre> 
<p></p> 
<h4>C算法源码</h4> 
<pre><code class="language-cpp">#include &lt;stdio.h&gt;

#define MAX(a,b) a &gt; b ? a : b

int getResult(int n, int nums[], int m);

int main() {
    int n;
    scanf(&#34;%d&#34;, &amp;n);

    int nums[n];
    int idx &#61; 0;
    while(scanf(&#34;%d&#34;, &amp;nums[idx&#43;&#43;])) {
        if(getchar() !&#61; &#39; &#39;) break;
    }

    int m;
    scanf(&#34;%d&#34;, &amp;m);

    printf(&#34;%d\n&#34;, getResult(n, nums, m));

    return 0;
}

int getResult(int n, int nums[], int m) {
    int sum &#61; 0;
    for(int i&#61;0; i&lt;m; i&#43;&#43;) {
        sum &#43;&#61; nums[i];
    }

    int ans &#61; sum;
    for(int i&#61;1; i&lt;&#61;n-m; i&#43;&#43;) {
        sum &#43;&#61; nums[i&#43;m-1] - nums[i-1];
        ans &#61; MAX(ans, sum);
    }

    return ans;
}
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>